package icu.zhhll.utils;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author zh
 * @date 2023/8/15 21:59
 */
public class RequestUtils {

    /**
     * 获取当前请求(只支持该请求为当前线程的)
     * 如果需要子线程也可以获取，需要在开启线程前进行设置
     *
     * @return
     * @see #setThreadInheritable()
     */
    public static HttpServletRequest getCurrentRequest() {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
        return requestAttributes.getRequest();

    }

    /**
     * 设置请求线程遗传
     * 如果需要在子线程获取当前请求，需要先设置线程遗传
     *
     * @return
     */
    public static boolean setThreadInheritable() {
        // 主线程先获取到请求信息
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 设置子线程共享
        RequestContextHolder.setRequestAttributes(requestAttributes, true);
        return true;
    }
}
